package com.gitee.cui.basic.use;

import com.gitee.cui.util.ThreadUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 守护线程中创建的普通线程，如果不去显示设置为用户线程，则默认都为守护线程
 * @author cuiqingqiang
 * @version 1.0
 * @date 2021/11/10 16:08
 **/
@Slf4j
public class DaemonCreateThread {

    private static final int SLEEP_GAP = 5000;

    private static final int TURN = 5;

    static class NormalThread extends Thread {

        private static int threadNo = 1;
        public NormalThread() {
            super("normalThread-" + threadNo);
            threadNo++;
        }

        @Override
        public void run() {
            while (true) {
                ThreadUtil.sleepMilliSeconds(SLEEP_GAP);
                log.info(getName() + " 守护状态为：{}", isDaemon());
            }
        }
    }

    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            for (int i = 1; i < TURN; i++) {
                NormalThread normalThread = new NormalThread();
                normalThread.setDaemon(false);
                normalThread.start();
            }
        }, "daemonThread");
        thread.setDaemon(true);
        thread.start();

        ThreadUtil.sleepMilliSeconds(SLEEP_GAP);
        log.info("{} 运行结束", ThreadUtil.getCurThreadName());
    }
}
